package com.library.service.impl;

import com.library.constant.IsAdminEnum;
import com.library.mapper.BookMapper;
import com.library.mapper.BorrowMapper;
import com.library.mapper.UserMapper;
import com.library.pojo.vo.UserVO;
import com.library.result.PageResult;
import com.library.result.Result;
import com.library.service.UserService;
import com.library.pojo.dto.user.*;
import com.library.pojo.entity.LibraryUsers;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final SqlSessionFactory sqlSessionFactory;

    public UserServiceImpl() {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 创建SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession(true);

            // 获取Mapper代理对象
            userMapper = sqlSession.getMapper(UserMapper.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询用户信息
     * @param userId 用户编号
     * @return 用户信息
     */
    @Override
    public UserVO selectUserInfo(int userId) {
        LibraryUsers userInfo = userMapper.selectById(userId);
        if (userInfo != null) {
            UserVO userVO = new UserVO();
            userVO.setUserId(userInfo.getUserId());
            userVO.setUsername(userInfo.getUsername());
            return userVO;
        }
        return null;
    }

    /**
     * 修改用户密码
     * @param userChangePasswordDTO 修改密码参数（必填：userId/oldPassword/newPassword）
     */
    @Override
    public int changePassword(UserChangePasswordDTO userChangePasswordDTO) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            // 参数校验
            if (userChangePasswordDTO == null || userChangePasswordDTO.getUserId() == null ||
                    userChangePasswordDTO.getOldPassword() == null || userChangePasswordDTO.getNewPassword() == null ||
                    userChangePasswordDTO.getOldPassword().isEmpty() || userChangePasswordDTO.getNewPassword().isEmpty()) {
                throw new IllegalArgumentException("用户ID、旧密码和新密码都不能为空");
            }
            //获得输入的新旧密码
            String oldPassword=userChangePasswordDTO.getOldPassword();
            String newPassword=userChangePasswordDTO.getNewPassword();
            //获得数据库里的旧密码
            LibraryUsers userInfo = userMapper.selectById(userChangePasswordDTO.getUserId());
            if(userInfo==null){
                return 0;
            }
            String currentOldpassword = userInfo.getPassword();
            //密码正确
            if(currentOldpassword.equals(oldPassword)){
                userInfo.setPassword(newPassword);
                userMapper.update(userInfo);
                return 1;
            }else{
                //抛出错误：旧密码错误
                return 0;
            }
        } catch (Exception e) {
            // 回滚事务
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }

    /**
     * 用户注册
     * @param userRegisterDTO 注册参数（可选：username/password/role等）
     */
    @Override
    public int register(UserRegisterDTO userRegisterDTO) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            // 参数校验
            if (userRegisterDTO == null || userRegisterDTO.getUsername() == null || userRegisterDTO.getPassword() == null || userRegisterDTO.getUsername().isEmpty() || userRegisterDTO.getPassword().isEmpty()) {
                throw new IllegalArgumentException("用户名和密码不能为空");
            }
            //用户名重了
            if(userMapper.selectByUserName(userRegisterDTO.getUsername())!=null){
                return 0;
            }
            LibraryUsers userInfo=new LibraryUsers();
            //对用户信息进行初始化
            userInfo.setIsAdmin(0);
            userInfo.setPassword(userRegisterDTO.getPassword());
            userInfo.setUsername(userRegisterDTO.getUsername());
            //调用mapper插入
            userMapper.insert(userInfo);
            return 1;
        } catch (Exception e) {
            // 回滚事务
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }

    /**
     * 用户登录
     * @param userLoginDTO 登录参数（必填：username/password）
     */
    @Override
    public LibraryUsers login(UserLoginDTO userLoginDTO) {
        // 将验证逻辑移入service层
        if (userLoginDTO == null || userLoginDTO.getUsername() == null || userLoginDTO.getPassword() == null || userLoginDTO.getUsername().isEmpty() || userLoginDTO.getPassword().isEmpty()) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }
        LibraryUsers userInfo = userMapper.selectByUserName(userLoginDTO.getUsername());
        // 用户名不存在
        if(userInfo == null){
            return null;
        }
        // 密码错误
        else if (!userInfo.getPassword().equals(userLoginDTO.getPassword())) {
            return null;
        }
        // 成功登录
        else{
            return userInfo;
        }
    }
    /**
     * 管理员分页查询用户
     * @param userPageQueryDTO 分页参数（必填：pageNum/pageSize；可选：userId/username关键词）
     * @return 分页用户列表
     */
    @Override
    public Result<PageResult> pageQuery(UserPageQueryDTO userPageQueryDTO) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try{
            int pageNum = userPageQueryDTO.getPageNum();
            int pageSize = userPageQueryDTO.getPageSize();
            int offset = (pageNum - 1) * pageSize;

            // 获取用户数据
            List<LibraryUsers> libraryUsers = userMapper.pageQuery(userPageQueryDTO.getUserId(), userPageQueryDTO.getUsername(), pageSize, offset);
            // 转换成vo对象
            List<UserVO> userVOS = libraryUsers.stream()
                    .filter(Objects::nonNull)
                    .map(userDTO -> new UserVO(userDTO.getUserId(), userDTO.getUsername())).toList();
            // 获取总记录数
            int total = userMapper.count();
            return Result.success(new PageResult(total, userVOS));
        } catch (Exception e) {
            // 回滚事务
            sqlSession.rollback();
            return null;
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }

    /**
     * 添加用户
     * @param userDTO 注册参数（可选：username/password/role等）
     */
    @Override
    public int insert(UserDTO userDTO) {
        //检查是否有空数据
        if(userDTO==null || userDTO.getUsername()==null ||
                userDTO.getPassword()==null || userDTO.getUsername().isEmpty() || userDTO.getPassword().isEmpty()){
            return 0;
        }
        //检测用户是否已经存在
        if(userMapper.selectByUserName(userDTO.getUsername())!=null){
            return 0;
        }
        LibraryUsers userInfo=new LibraryUsers();
        //初始化用户数据
        userInfo.setIsAdmin(IsAdminEnum.NOT_ADMIN.getCode());
        userInfo.setPassword(userDTO.getPassword());
        userInfo.setUsername(userDTO.getUsername());
        //调用mapper插入
        userMapper.insert(userInfo);
        return 1;
    }

    /**
     * 根据用户编号修改用户信息
     * @param userDTO 注册参数（可选：username/password/role等）
     */
    @Override
    public int update(UserDTO userDTO) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //检查是否有空数据
        if(userDTO==null || userDTO.getUsername()==null ||
                userDTO.getPassword()==null || userDTO.getUsername().isEmpty() || userDTO.getPassword().isEmpty()){
            return 0;
        }
        LibraryUsers userInfo=new LibraryUsers();
        //将DTO转为Users输入mapper
        userInfo.setUserId(userDTO.getUserId());
        userInfo.setPassword(userDTO.getPassword());
        userInfo.setUsername(userDTO.getUsername());
        //调用mapper更新
        userMapper.update(userInfo);
        return 1;
    }

    /**
     * 根据用户编号删除用户
     * @param userId 用户编号
     */
    @Override
    public int deleteById(int userId) {
        // 开启事务
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        try {
            //用户不存在
            if(userMapper.selectById(userId)==null){
                return 0;
            }
            //调用mapper删除
            userMapper.deleteById(userId);
            return 1;
        } catch (Exception e) {
            // 回滚事务
            sqlSession.rollback();
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            sqlSession.close();
        }
    }
}
